import os
import struct

OUTPUT      = "output"
BOOT_SRC    = "./bootloader/boot.asm"
BOOT_BIN    = "./output/boot.bin"
LOADER_SRC  = "./bootloader/loader.asm"
LOADER_BIN  = "./output/loader.bin"
IMG         = "./output/a.img"


def main():
    # 创建文件夹 output
    if not os.path.exists(OUTPUT):
        os.mkdir(OUTPUT)

    # 编译 boot.asm
    src = BOOT_SRC
    out = BOOT_BIN
    cmd_str = "nasm " + src + " -o " + out
    print(cmd_str)
    os.system(cmd_str)

    # 编译 loader.asm
    src = LOADER_SRC
    out = LOADER_BIN
    cmd_str = "nasm " + src + " -o " + out
    print(cmd_str)
    os.system(cmd_str)

    # 创建一个 60M 的虚拟硬盘，由于搭了两套开发环境，所以这里 bximage 有两种命令格式
    # 使用 “bximage --help” 命令可获得 bximage 的用法
    # 另一个：bximage $@ -func="create" -hd=60 -imgmode="flat" -q
    cmd_str = "bximage " + IMG + ' -hd -size=60 -mode="flat" -q'
    print(cmd_str)
    os.system(cmd_str)

    # 将 boot.bin 写入硬盘 a.img 的第 0 个扇区
    cmd_str = "dd if=" + BOOT_BIN + " of=" + IMG + " bs=512 count=1 conv=notrunc"
    print(cmd_str)
    os.system(cmd_str)

    # 获取 loader.bin 所占扇区数
    stats = os.stat(LOADER_BIN)
    loader_blocks = int(stats.st_size / 512) + 1 

	# 将 loader.bin 写入硬盘 a.img 的第 2 个扇区
    cmd_str = "dd if=" + LOADER_BIN + " of=" + IMG + " bs=512 count=" + str(loader_blocks) + " seek=2 conv=notrunc"
    print(cmd_str)
    os.system(cmd_str)
    

    # 读取 IMG 文件，将 loader.bin 扇区数写到第二个扇区前两个字节中
    img = []
    with open(IMG, "rb") as f:
        data = f.read()
        for i in range(len(data)):
            img.append(data[i])
        img[512] = loader_blocks
        img[513] = loader_blocks>>8
    with open(IMG, 'wb') as f:  
        for x in img:
            f.write(struct.pack('B', x))

    print("Success!")


if __name__ == '__main__':
    main()